package demo;

import java.io.FileOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;

public class RSAKeyPairGenerator {
    public static void main(String[] args) throws Exception {
// 生成RSA密钥对
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048); // 指定密钥长度为2048位
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

// 将公私钥分别保存到文件
        writeToFile("./key/publicKey.pub", keyPair.getPublic().getEncoded());
        writeToFile("./key/privateKey.pri", keyPair.getPrivate().getEncoded());
    }

    private static void writeToFile(String fileName, byte[] content) throws Exception {
        try (FileOutputStream outputStream = new FileOutputStream(fileName)) {
            outputStream.write(content);
            outputStream.flush();
        }
    }
}
